<template>
  <div class="recharge_box">
    <customDialog
      :title="'充值档位'"
      :dialogVisible="dialogVisible"
      @close="closeDialog(ruleFormRef)"
      @cancel="closeDialog(ruleFormRef)"
      :cancelText="'关闭'"
      @confirm="confirmDialog(ruleFormRef)"
      width="680"
    >
      <div>
        <div class="tab_box">
          <span
            class="comm_span"
            :class="handleActive(1)"
            @click="handleClick(1)"
          >
            金币
          </span>
          <span
            class="comm_span"
            :class="handleActive(3)"
            @click="handleClick(3)"
          >
            会员
          </span>
          <span
            class="comm_span"
            :class="handleActive(2)"
            @click="handleClick(2)"
          >
            解锁全集
          </span>
        </div>
        <el-form
          ref="ruleFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          label-position="left"
        >
          <el-row>
            <el-col :span="20">
              <el-form-item label="充值金额（元）" prop="total">
                <el-input
                  v-model="formData.total"
                  @blur="handleBlur(formData.total)"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item
                label="赠送金额（元）"
                prop="item1Data"
                v-if="formData.itemClass == 1"
              >
                <el-input
                  v-model="formData.item1Data"
                  @blur="handleBlur2(formData.item1Data)"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="总金币" v-if="formData.itemClass == 1">
                <span>{{ +formData.total ? handlePrice() : "0" }}</span>
                &nbsp;金币
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item
                label="会员天数"
                prop="itemData"
                v-if="formData.itemClass == 3"
              >
                <el-input v-model="formData.itemData" style="width: 358px" />
                &nbsp; 天
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="引导文案" prop="guidance">
                <el-input v-model="formData.guidance" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="20">
              <el-form-item label="左角标文案" prop="primaryBadage">
                <el-input
                  v-model.trim="formData.primaryBadage"
                  placeholder="建议最多输入7个字符"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="右角标文案" prop="secondaryBadge">
                <el-input
                  v-model="formData.secondaryBadge"
                  placeholder="建议最多输入7个字符"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="20">
              <el-form-item label="样式主题" prop="theme">
                <el-select
                  v-model="formData.theme"
                  placeholder="请选择"
                  class="bg_img_box"
                  @change="handleChange"
                >
                  <template v-for="(item, index) in bgImgList" :key="index">
                    <el-option
                      :label="item.label"
                      :value="item.theme"
                      class="img_option"
                    >
                      <img
                        :src="item.value"
                        style="width: 164px; height: 74px"
                      />
                    </el-option>
                  </template>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="20">
              <el-form-item label="默认选中" prop="isSelected">
                <el-switch
                  v-model="formData.isSelected"
                  inline-prompt
                  active-text="是"
                  inactive-text="否"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <p class="grey">
            充值模板中必须定义1个为默认选中，用户在充值时默认选中这一项
          </p>
        </el-form>
      </div>
    </customDialog>
  </div>
</template>

<script lang="ts" setup>
import customDialog from "@/components/CustomDialog/index.vue";
import { ref, reactive, toRefs, onMounted, computed } from "vue";
import type { FormInstance } from "element-plus";
import { mul } from "@/utils/index";
import { cloneDeep } from "lodash-es";

const props = defineProps({
  // 是否展示解锁全集
  isUnlock: {
    type: Boolean,
    default: true,
  },
});

const activeName = ref<string>("1");
const ruleFormRef = ref<FormInstance>();
const dialogVisible = ref<boolean>(false);
import black_theme from "@/assets/img/black_theme.jpg";
import orange_theme from "@/assets/img/orange_theme.jpg";
import grey_theme from "@/assets/img/grey_theme.jpg";
// import plain_theme from "@/assets/img/plain.jpg";
// import silvery_theme from "@/assets/img/grey.jpg";
// import lightYellow_theme from "@/assets/img/lightYellow.jpg";
import orangeYellow_theme from "@/assets/img/orangeYellow.jpg";

import theme4 from "@/assets/img/theme4.png";
import theme5 from "@/assets/img/theme5.png";
import theme6 from "@/assets/img/theme6.png";
const form = {
  description: "",
  total: 0,
  itemClass: 1, // 充值类型：1 - 金币，2 - 解锁全集，3 - VIP
  itemData: 0, // 充值类型对应值 如果 ItemClass 为 1，则表示金币数量 如果 ItemClass 为 2，则表示短剧 Id, 如果 ItemClass 为 3 则表示 VIP 天数
  item1Class: 1,
  item1Data: 0,
  isSelected: false,
  theme: "",
  primaryBadage: "",
  secondaryBadge: "",
  guidance: "",
  bgImage: "1.jpg",
  effect: "2.jpg",
  // badge: ""
};
const formData = ref(Object.assign({}, cloneDeep(form)));
const tempData = ref(); // 备份原数据
const copyTotal = ref(); // 备份价格
const list = [
  { label: "背景—银色", value: grey_theme, theme: "1" },
  { label: "背景—橙色", value: orange_theme, theme: "2" },
  { label: "背景-黑金色", value: black_theme, theme: "3" },
  { label: "背景-浅白色", value: theme4, theme: "4" },
  { label: "背景-灰色", value: theme5, theme: "5" },
  { label: "背景-浅黄色", value: theme6, theme: "6" },
  { label: "背景-橙黄色", value: orangeYellow_theme, theme: "7" },
];
const bgImgList = ref(list);

const handleChange = (val: any) => {
  console.log("这是点击主题---", val);
  // if (val == "7") {
  //   handleClick(3);
  // }
};

// 充值金额规则
const totalRules = (rule: any, value: any, callback: any) => {
  let reg = /^(([1-9]{1}\d*)|(0{1}))(\.\d{1,2})?$/; // 最多保留2位小数
  let fieldText = rule?.field === "total" ? "充值" : "赠送";
  if (fieldText === "充值") {
    if (!+value || +value < 0) {
      return callback(new Error(`请输入大于0的数字`));
    } else if (!reg.test(value)) {
      return callback(new Error("金额最多保留两位小数"));
    } else if (+value > 999.99) {
      return callback(new Error(`充值金额最大支持 999.99 元`));
    } else {
      callback();
    }
  } else {
    if ((!+value && +value != 0) || +value < 0) {
      return callback(new Error(`请输入大于0的数字`));
    } else if (!reg.test(value)) {
      return callback(new Error("金额最多保留两位小数"));
    } else if (+value > +formData.value.total * 5) {
      return callback(new Error(`赠送金额最大不能超过充值金额的5倍`));
    } else {
      callback();
    }
  }
};

const itemDataRules = (rule: any, value: any, callback: any) => {
  let reg = /^[1-9]\d*$/; // 大于0的整数
  if (!+value && value != 0) {
    return callback(new Error("请输入大于1-999之间的整数"));
  } else if (!reg.test(value) || +value > 999) {
    return callback(new Error("请输入大于1-999之间的整数"));
  } else {
    callback();
  }
};

const rules = reactive({
  total: [{ required: true, validator: totalRules, trigger: "change" }],
  item1Data: [{ required: false, validator: totalRules, trigger: "blur" }],
  itemData: [{ required: false, validator: itemDataRules, trigger: "blur" }],
  theme: [{ required: true, message: "请选择主题", trigger: "blur" }],
});

// 充值金额小数梳理
const handleBlur = (val: number | string) => {
  formData.value.total = isNaN(Number(val)) ? "0.00" : Number(val).toFixed(2);
};

// 赠送金额小数梳理
const handleBlur2 = (val: number | string) => {
  formData.value.item1Data = isNaN(Number(val))
    ? "0.00"
    : Number(val).toFixed(2);
};

// 总金币处理
const handlePrice = () => {
  return Math.floor(
    (Number(formData.value.total) + Number(formData.value.item1Data)) * 100
  );
};

// 样式处理
const handleActive = (val: number) => {
  return formData.value.itemClass == val ? "activeC" : "";
};

// 切换tab
const handleClick = (val: number) => {
  formData.value.itemClass = val;
  bgImgList.value = Object.assign([], list);
  if (val === 3) {
    formData.value.itemData = 365;
    formData.value.total = 365;
    // bgImgList.value = [
    //   { label: "背景-橙黄色", value: orangeYellow_theme, theme: "7" },
    // ];
    // formData.value.theme = "7";
  } else if (val === 1) {
    tempData.value = cloneDeep(tempData.value);
    formData.value = tempData.value; // 切换还原数据
    formData.value.total = copyTotal.value;
  } else {
    formData.value.total = 199;
    formData.value.itemData = "";
  }
};

// 关闭
const closeDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  dialogVisible.value = false;
  activeName.value = "1";
  formData.value.total = +formData.value.total * 100; // 还原初始数据
  formData.value.item1Data = +formData.value.item1Data * 100; // 还原初始数据
};

// 成功
const emit = defineEmits(["success"]);
const confirmDialog = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formData.value.total = Number(formData.value.total);
  formEl.validate((valid) => {
    if (valid) {
      let type = formData.value.itemClass;
      let totalNum1 = mul(formData.value.total, "100"); // 充值金额
      let totalNum2 = formData.value.item1Data
        ? mul(formData.value.item1Data, "100")
        : ""; // 增送金额

      formData.value.total = totalNum1;

      //itemData:  当ItemClass 0:无充值， 1：则表示金币数量 如果 ItemClass  2：则表示短剧 Id, 如果 ItemClass 3：则表示 VIP 天数
      // 充值模板管理这里是没有选剧功能的，所以短剧 id 传 0
      formData.value.itemData =
        type === 1 ? totalNum1 : type === 2 ? 0 : formData.value.itemData;
      formData.value.item1Data = type === 1 ? Number(totalNum2) : 0;
      let temp = formData.value.item1Data
        ? `+${formData.value.item1Data}币`
        : "";
      let totalCoin = `获${formData.value.itemData}币${temp}`;
      formData.value.description =
        type === 3 ? "365天至尊大会员" : type === 2 ? "解锁全集" : totalCoin;
      formData.value.item1Class = formData.value.item1Data ? type : 0;
      formData.value.primaryBadage = formData.value.primaryBadage.replace(
        /\s*/g,
        ""
      );
      formData.value.secondaryBadge = formData.value.secondaryBadge.replace(
        /\s*/g,
        ""
      );
      formData.value.guidance = formData.value.guidance.replace(/\s*/g, "");
      dialogVisible.value = false;
      emit("success", formData.value);
    }
  });
};

// 父级电子显示dialog
const showDialog = (val: Record<string, any>) => {
  console.log("接受充值档位数据------", val);
  let copyData = cloneDeep(val);
  // 当为 item1Class = 1 为金币时,转换金额单位 分 -> 元
  copyData.total = Number(copyData.total / 100).toFixed(2);
  if (copyData.item1Class === 1) {
    copyData.item1Data = Number(copyData.item1Data / 100).toFixed(2);
  }
  // 备份初始数据
  tempData.value = cloneDeep(copyData);
  copyTotal.value = cloneDeep(Number(val.total / 100).toFixed(2));

  formData.value = cloneDeep(copyData) || "";
  // console.log("formData-----", formData.value);

  dialogVisible.value = true;
};

defineExpose({
  showDialog,
});
</script>
<style scoped lang="scss">
.recharge_box {
  .tab_box {
    display: flex;
    margin-bottom: 20px;
    font-size: 17px;
    color: #333;

    .comm_span {
      margin-right: 20px;
      cursor: pointer;
    }

    .activeC {
      position: relative;
      color: #006eff;
    }

    .activeC::after {
      position: absolute;
      bottom: -4px;
      left: 0;
      width: 100%;
      height: 2px;
      content: "";
      background-color: #006eff;
      opacity: 0.6;
    }
  }

  :deep(.el-dialog__body) {
    padding: 6px 40px;
  }
}
</style>
